<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { FileItem } from '@arco-design/web-vue';

  import { removeFileApi } from '@/api/system/excel-import';
  import { submitImportApi } from '@/api/system/user';
  import { useForm } from '@/hooks/form';
  import { getToken } from '@/utils/auth';
  import setting from '@/utils/axios/setting';
  import { getTenantCode } from '@/utils/tenant';

  const baseURL = setting.baseURL;

  const tempFileId = ref('');

  const formSchema = computed<FormSchema[]>(() => {
    return [
      {
        field: 'excelFile',
        type: 'upload',
        props: {
          accept:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          action: `${baseURL}/system/excelImport/uploadFile`,
          draggable: true,
          headers: { Authorization: getToken(), Tenant: getTenantCode() },
          limit: 1,
          listType: 'text',
          onSuccess: async (res: FileItem) => {
            tempFileId.value = res.response.data.tempId;
          },
          onBeforeRemove: async () => {
            const res = await removeFileApi(tempFileId.value);
            if (!!res) {
              tempFileId.value = '';
              return Promise.resolve(true);
            } else {
              return Promise.reject();
            }
          },
        },
      },
    ];
  });

  const rules = reactive({});

  const { formRegister } = useForm();

  const submitImport = async () => {
    if (tempFileId.value) {
      const res = await submitImportApi(tempFileId.value);
      if (res) {
        MessageInfo.success('提交成功');
        return true;
      } else {
        MessageInfo.error('提交失败');
        return false;
      }
    } else {
      MessageInfo.warning('请先上传附件！');
      return false;
    }
  };

  defineExpose({
    submitImport,
  });
</script>
